package com.xxrl.shop.config.handler;

import com.xxrl.shop.domain.SysPermission;
import com.xxrl.shop.service.SysPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author mis
 */
@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static final Logger logger = LoggerFactory.getLogger(CustomizeFilterInvocationSecurityMetadataSource.class);
    private final SysPermissionService sysPermissionService;

    @Value("${my.showLog}")
    private Boolean showDebugLog;

    public CustomizeFilterInvocationSecurityMetadataSource(SysPermissionService sysPermissionService) {
        this.sysPermissionService = sysPermissionService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o)  {
        //获取请求地址
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<ConfigAttribute> res = new ArrayList<>();
        int idx = requestUrl.indexOf('?');
        if (idx != -1) {
            requestUrl = requestUrl.substring(0,idx);
        }
        //查询具体某个接口的权限
        List<SysPermission> permissions = sysPermissionService.getPermissionByPath(requestUrl);
        if (permissions == null || permissions.isEmpty()) {
            return res;
        }
        if (showDebugLog) {
            logger.info("request path: {}. permission size:{}",requestUrl,res.size());
        }
        for (SysPermission permission : permissions) {
            res.add(permission::getRole);
        }
        return res;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new ArrayList<>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
